package com.xujie.sportsmeeting.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.CompetitionEventDTO;
import com.xujie.sportsmeeting.entity.CompetitionEvent;
import com.xujie.sportsmeeting.service.CompetitionEventService;
import com.xujie.sportsmeeting.vo.CompetitionEventVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDateTime;

/**
 * 比赛项目管理控制器
 */
@Tag(name = "比赛项目管理", description = "比赛项目的增删改查接口")
@RestController
@RequestMapping("/events")
@RequiredArgsConstructor
public class CompetitionEventController {

    private final CompetitionEventService competitionEventService;

    @Operation(summary = "分页查询比赛项目")
    @GetMapping
    @PreAuthorize("hasAnyAuthority('event', 'system:user', 'athlete')")
    public Result<Page<CompetitionEventVO>> pageEvents(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer eventType,
            @RequestParam(required = false) Integer genderLimit,
            @RequestParam(required = false) Integer status) {
        
        Page<CompetitionEvent> page = new Page<>(current, size);
        LambdaQueryWrapper<CompetitionEvent> wrapper = new LambdaQueryWrapper<>();
        
        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.like(CompetitionEvent::getEventName, keyword)
                   .or().like(CompetitionEvent::getEventCode, keyword)
                   .or().like(CompetitionEvent::getVenue, keyword);
        }
        
        // 条件筛选
        if (eventType != null) {
            wrapper.eq(CompetitionEvent::getEventType, eventType);
        }
        if (genderLimit != null) {
            wrapper.eq(CompetitionEvent::getGenderLimit, genderLimit);
        }
        if (status != null) {
            wrapper.eq(CompetitionEvent::getStatus, status);
        }
        
        wrapper.orderByDesc(CompetitionEvent::getCreateTime);
        
        Page<CompetitionEvent> result = competitionEventService.page(page, wrapper);
        
        // 转换为VO
        Page<CompetitionEventVO> voPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        voPage.setRecords(result.getRecords().stream().map(event -> {
            CompetitionEventVO vo = new CompetitionEventVO();
            BeanUtils.copyProperties(event, vo);
            
            // 设置当前报名人数
            vo.setCurrentRegistrations(competitionEventService.getRegistrationCount(event.getId()));
            
            // 设置是否可以报名
            vo.setCanRegister(competitionEventService.canRegister(event.getId()));
            
            return vo;
        }).toList());
        
        return Result.success(voPage);
    }

    @Operation(summary = "根据ID查询比赛项目")
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('event', 'system:user', 'athlete')")
    public Result<CompetitionEventVO> getEvent(@PathVariable Long id) {
        CompetitionEvent event = competitionEventService.getById(id);
        if (event == null) {
            return Result.error("比赛项目不存在");
        }
        
        CompetitionEventVO vo = new CompetitionEventVO();
        BeanUtils.copyProperties(event, vo);
        vo.setCurrentRegistrations(competitionEventService.getRegistrationCount(id));
        vo.setCanRegister(competitionEventService.canRegister(id));
        
        return Result.success(vo);
    }

    @Operation(summary = "新增比赛项目")
    @PostMapping
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> addEvent(@Valid @RequestBody CompetitionEventDTO eventDTO) {
        // 检查项目编码是否存在
        if (competitionEventService.existsByEventCode(eventDTO.getEventCode())) {
            return Result.error("项目编码已存在");
        }
        
        CompetitionEvent event = new CompetitionEvent();
        BeanUtils.copyProperties(eventDTO, event);
        event.setStatus(1); // 默认正常状态
        
        competitionEventService.save(event);
        return Result.success("比赛项目添加成功");
    }

    @Operation(summary = "更新比赛项目")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> updateEvent(@PathVariable Long id, @Valid @RequestBody CompetitionEventDTO eventDTO) {
        CompetitionEvent existEvent = competitionEventService.getById(id);
        if (existEvent == null) {
            return Result.error("比赛项目不存在");
        }
        
        // 检查项目编码是否被其他项目使用
        CompetitionEvent eventWithSameCode = competitionEventService.findByEventCode(eventDTO.getEventCode());
        if (eventWithSameCode != null && !eventWithSameCode.getId().equals(id)) {
            return Result.error("项目编码已被其他项目使用");
        }
        
        CompetitionEvent event = new CompetitionEvent();
        BeanUtils.copyProperties(eventDTO, event);
        event.setId(id);
        
        competitionEventService.updateById(event);
        return Result.success("比赛项目更新成功");
    }

    @Operation(summary = "删除比赛项目")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> deleteEvent(@PathVariable Long id) {
        CompetitionEvent event = competitionEventService.getById(id);
        if (event == null) {
            return Result.error("比赛项目不存在");
        }
        
        // 检查是否有报名记录
        long registrationCount = competitionEventService.getRegistrationCount(id);
        if (registrationCount > 0) {
            return Result.error("该项目已有报名记录，不能删除");
        }
        
        competitionEventService.removeById(id);
        return Result.success("比赛项目删除成功");
    }

    @Operation(summary = "批量删除比赛项目")
    @DeleteMapping("/batch")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> batchDeleteEvents(@RequestBody Long[] ids) {
        for (Long id : ids) {
            long registrationCount = competitionEventService.getRegistrationCount(id);
            if (registrationCount > 0) {
                return Result.error("项目ID " + id + " 已有报名记录，不能删除");
            }
        }
        
        competitionEventService.removeBatchByIds(java.util.Arrays.asList(ids));
        return Result.success("批量删除成功");
    }

    @Operation(summary = "更新项目状态")
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> updateEventStatus(@PathVariable Long id, @RequestParam Integer status) {
        CompetitionEvent event = competitionEventService.getById(id);
        if (event == null) {
            return Result.error("比赛项目不存在");
        }
        
        competitionEventService.updateEventStatus(id, status);
        return Result.success("项目状态更新成功");
    }

    @Operation(summary = "根据项目编码查询项目")
    @GetMapping("/code/{eventCode}")
    @PreAuthorize("hasAnyAuthority('event', 'system:user', 'athlete')")
    public Result<CompetitionEventVO> getEventByCode(@PathVariable String eventCode) {
        CompetitionEvent event = competitionEventService.findByEventCode(eventCode);
        if (event == null) {
            return Result.error("比赛项目不存在");
        }
        
        CompetitionEventVO vo = new CompetitionEventVO();
        BeanUtils.copyProperties(event, vo);
        vo.setCurrentRegistrations(competitionEventService.getRegistrationCount(event.getId()));
        vo.setCanRegister(competitionEventService.canRegister(event.getId()));
        
        return Result.success(vo);
    }

    @Operation(summary = "获取可报名的项目列表")
    @GetMapping("/available")
    @PreAuthorize("hasAnyAuthority('athlete', 'system:user')")
    public Result<Page<CompetitionEventVO>> getAvailableEvents(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) Integer genderLimit) {
        
        Page<CompetitionEvent> page = new Page<>(current, size);
        LambdaQueryWrapper<CompetitionEvent> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.eq(CompetitionEvent::getStatus, 2) // 报名中
               .le(CompetitionEvent::getRegistrationStartTime, LocalDateTime.now())
               .ge(CompetitionEvent::getRegistrationEndTime, LocalDateTime.now());
        
        if (genderLimit != null) {
            wrapper.and(w -> w.eq(CompetitionEvent::getGenderLimit, 0)
                             .or().eq(CompetitionEvent::getGenderLimit, genderLimit));
        }
        
        wrapper.orderByAsc(CompetitionEvent::getCompetitionTime);
        
        Page<CompetitionEvent> result = competitionEventService.page(page, wrapper);
        
        // 转换为VO并过滤已满的项目
        Page<CompetitionEventVO> voPage = new Page<>(result.getCurrent(), result.getSize());
        voPage.setRecords(result.getRecords().stream()
                .filter(event -> competitionEventService.canRegister(event.getId()))
                .map(event -> {
                    CompetitionEventVO vo = new CompetitionEventVO();
                    BeanUtils.copyProperties(event, vo);
                    vo.setCurrentRegistrations(competitionEventService.getRegistrationCount(event.getId()));
                    vo.setCanRegister(true);
                    return vo;
                }).toList());
        
        voPage.setTotal(voPage.getRecords().size());
        
        return Result.success(voPage);
    }
}
